package httpserver

import (
	"gitee.com/amwfhv/tge/options"
	"github.com/gin-gonic/gin"
)

type Config struct {
	Mode            string
	Healthz         bool
	EnableProfiling bool
	EnableMetrics   bool
	Middlewares     []string
	SecureServing   *options.SecureServingInfo
	InsecureServing *options.InsecureServingInfo
}

type Option func(*Config)

func WithServerRun(s *options.ServerRunOptions) Option {
	return func(c *Config) {
		if s != nil {
			c.Mode = s.Mode
			c.Healthz = s.Healthz
			c.Middlewares = s.Middlewares
		}
	}
}

func WithFeature(fo *options.FeatureOptions) Option {
	return func(c *Config) {
		if fo != nil {
			c.EnableProfiling = fo.EnableProfiling
			c.EnableMetrics = fo.EnableMetrics
		}
	}
}

func WithSecureServing(ss *options.SecureServingOptions) Option {
	return func(c *Config) {
		if ss != nil {
			c.SecureServing.BindAddress = ss.BindAddress
			c.SecureServing.BindPort = ss.BindPort
			c.SecureServing.CertKey.CertFile = ss.ServerCert.CertFile
			c.SecureServing.CertKey.KeyFile = ss.ServerCert.KeyFile
		}
	}
}

func WithInsecureServing(is *options.InsecureServingOptions) Option {
	return func(c *Config) {
		if is != nil {
			c.InsecureServing.BindAddress = is.BindAddress
			c.InsecureServing.BindPort = is.BindPort
		}
	}
}

func NewConfig(opts ...Option) *Config {
	ss := options.NewSecureServingOptions()
	is := options.NewInscureServingOptions()
	c := &Config{
		Mode:            gin.DebugMode,
		Healthz:         true,
		EnableProfiling: true,
		EnableMetrics:   true,
		Middlewares:     []string{},
		SecureServing: &options.SecureServingInfo{
			BindAddress: ss.BindAddress,
			BindPort:    ss.BindPort,
		},
		InsecureServing: &options.InsecureServingInfo{
			BindAddress: is.BindAddress,
			BindPort:    is.BindPort,
		},
	}
	for _, o := range opts {
		o(c)
	}
	return c
}
